﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Collections;
using ShareB.Providers;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;


namespace ShareB.Models
{

    #region Models
    [PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "The new password and confirmation password do not match.")]
    public class ChangePasswordModel
    {
        [Required]
        [DataType(DataType.Password)]
        [DisplayName("Current password")]
        public string OldPassword { get; set; }

        [Required]
        [ValidatePasswordLength]
        [DataType(DataType.Password)]
        [DisplayName("New password")]
        public string NewPassword { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [DisplayName("Confirm new password")]
        public string ConfirmPassword { get; set; }
    }

    public class LogOnModel
    {
        [Required]
        [DisplayName("User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [DisplayName("Password")]
        public string Password { get; set; }

        [DisplayName("Remember me?")]
        public bool RememberMe { get; set; }
    }

    [PropertiesMustMatch("Password", "ConfirmPassword", ErrorMessage = "The password and confirmation password do not match.")]
    public class RegisterModel
    {
        // -------------- Required Fields -----------
        [Required]
        [DisplayName("User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.EmailAddress)]
        [DisplayName("Email address")]
        public string Email { get; set; }

        [Required]
        [ValidatePasswordLength]
        [DataType(DataType.Password)]
        [DisplayName("Password")]
        public string Password { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [DisplayName("Confirm password")]
        public string ConfirmPassword { get; set; }

        [Required]
        [DisplayName("First name")]
        public string FirstName { get; set; }

        [Required]
        [DisplayName("Last name")]
        public string LastName { get; set; }

        // -------------- optional Fields -----------
        [DisplayName("Address")]
        public string Address { get; set; }

        
        [DisplayName("Photograph")]
        [ValidImage]
        public HttpPostedFileBase Photograph { get; set; }

    }

    //odelo para visualizaçao do profile apenas
    public class ProfileModel
    {

        //user personal information

        [Required]
        [DisplayName("UserID")]
        public int UserID { get; set; }

        [Required]
        [DisplayName("User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.EmailAddress)]
        [DisplayName("Email address")]
        public string Email { get; set; }

        [Required]
        [ValidatePasswordLength]
        [DataType(DataType.Password)]
        [DisplayName("Password")]
        public string Password { get; set; }

        [Required]
        [DisplayName("First name")]
        public string FirstName { get; set; }

        [Required]
        [DisplayName("Last name")]
        public string LastName { get; set; }

        [DisplayName("Address")]
        public string Address { get; set; }


        [DisplayName("Photograph")]
        public byte[] Photograph { get; set; }

        //users related information
        [DisplayName("Publishers")]
        public List<PublisherModel> Publishers { get; set; }

        [DisplayName("Followers")]
        public List<FollowerModel> Followers { get; set; }


        //construtor default
        public ProfileModel()
        {
            Publishers = new List<PublisherModel>();
            Followers = new List<FollowerModel>();
        }

        //construtor a partir de um user da BD
        public ProfileModel(User user)
        {
            UserID = user.UserID;
            UserName = user.Username;
            Email = user.Email;
            Password = user.Password;
            FirstName = user.FirstName;
            LastName = user.LastName;
            Address = user.Address;
            //Falta converter foto para display
            //Photograph = user.Foto;
            Photograph = null;
            Publishers = new List<PublisherModel>();
            Followers = new List<FollowerModel>();
        }

    }



    #endregion

    #region Services
    // The FormsAuthentication type is sealed and contains static members, so it is difficult to
    // unit test code that calls its members. The interface and helper class below demonstrate
    // how to create an abstract wrapper around such a type in order to make the AccountController
    // code unit testable.

    public interface IMembershipService
    {
        int MinPasswordLength { get; }

        //To authorize users
        bool ValidateUser(string userName, string password);
        
        //Not implemneted
        bool ChangePassword(string userName, string oldPassword, string newPassword);

        //To register new users
        MembershipCreateStatus CreateUser(string userName, string password, string email, string firstName, string lastName, string address, HttpPostedFileBase photograph);

        //To edit users profile
        MembershipCreateStatus EditUser(ProfileModel model);

        //Fetch user profile
        ProfileModel GetProfile(string userName);

        //get id
        int GetUserID(string username);
    }

    public class UserMembershipService : IMembershipService
    {
        private readonly ShareBMembershipProvider _provider;
        ShareBDataContext db = new ShareBDataContext();

        public UserMembershipService()
            : this(null)
        {
        }

        //Implements the provider
        public UserMembershipService(MembershipProvider provider)
        {
            _provider = (ShareBMembershipProvider)(provider ?? Membership.Provider);
        }

        //gets minimal password size
        public int MinPasswordLength
        {
            get
            {
                return _provider.MinRequiredPasswordLength;
            }
        }

        //Validates users authoring
        public bool ValidateUser(string userName, string password)
        {
            //handles user input
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");

            //calls provider service for validation
            return _provider.ValidateUser(userName, password);
        }

        //Handles users Registration
        public MembershipCreateStatus CreateUser(string userName, string password, string email, string firstName, string lastName, string address, HttpPostedFileBase photograph)
        {
            //handling user input for required fields
            //required fields
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
            if (String.IsNullOrEmpty(firstName)) throw new ArgumentException("Value cannot be null or empty.", "firstName");
            if (String.IsNullOrEmpty(lastName)) throw new ArgumentException("Value cannot be null or empty.", "lastName");

            //optional fields
            

            MembershipCreateStatus status;
            _provider.CreateUser(userName, password, email, firstName, lastName, address, PrepImageForUpload(photograph), null, null, true, null, out status);
            return status;
        }

        //Serviço para guardar os dados de ediçao de um user
        public MembershipCreateStatus EditUser(ProfileModel model)
        {
            //handling user input for required fields
            //required fields
            if (String.IsNullOrEmpty(model.UserName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(model.Password)) throw new ArgumentException("Value cannot be null or empty.", "password");
            if (String.IsNullOrEmpty(model.Email)) throw new ArgumentException("Value cannot be null or empty.", "email");
            if (String.IsNullOrEmpty(model.FirstName)) throw new ArgumentException("Value cannot be null or empty.", "firstName");
            if (String.IsNullOrEmpty(model.LastName)) throw new ArgumentException("Value cannot be null or empty.", "lastName");


            MembershipCreateStatus status;
            // fazer pre-verificacao da password
            if (!_provider.IsValidPassword(model.Password))
            {
                status = MembershipCreateStatus.InvalidPassword;
            }

            if (!_provider.IsValidEmail(model.Email))
            {
                status = MembershipCreateStatus.InvalidEmail;
            }

            string _user = _provider.GetUserNameByEmail(model.Email);
            if (_user != null && _user != model.UserName)
            { //verifica se email ja esta atribuido
                status = MembershipCreateStatus.DuplicateEmail;
            }
            else
            {
                //criar novo user e configurar
                User u = db.Users.Single(c => c.UserID == model.UserID);

                u.Username = model.UserName;
                u.Password = model.Password;
                u.Email = model.Email;
                u.Type = "Regular User";
                u.Disabled = false;
                u.FirstName = model.FirstName;
                u.LastName = model.LastName;
                u.Address = model.Address;
                u.Foto = null;
                
                db.SubmitChanges();                         //submissão na base de daodos
                status = MembershipCreateStatus.Success;
            }

            return status;
        }

        public bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            //handling user input
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
            if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Value cannot be null or empty.", "newPassword");

            // The underlying ChangePassword() will throw an exception rather
            // than return false in certain failure scenarios.
            try
            {
                MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */);
                return currentUser.ChangePassword(oldPassword, newPassword);
            }
            catch (ArgumentException)
            {
                return false;
            }
            catch (MembershipPasswordException)
            {
                return false;
            }
        }


        //tratar a imagem para guardar na BD
        private static byte[] PrepImageForUpload(HttpPostedFileBase FileData)
        {
            // se for null
            if (FileData == null)
                return null;

            // se nao for converte
            using (Bitmap origImage = new Bitmap(FileData.InputStream))
            {
                int maxWidth = 165;

                int newWidth = origImage.Width;
                int newHeight = origImage.Height;
                if (origImage.Width < newWidth) //Force to max width
                {
                    newWidth = maxWidth;
                    newHeight = origImage.Height * maxWidth / origImage.Width;
                }

                using (Bitmap newImage = new Bitmap(newWidth, newHeight))
                {
                    using (Graphics gr = Graphics.FromImage(newImage))
                    {
                        gr.SmoothingMode = SmoothingMode.AntiAlias;
                        gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        gr.DrawImage(origImage, new Rectangle(0, 0, newWidth, newHeight));

                        MemoryStream ms = new MemoryStream();
                        newImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                        return ms.ToArray();
                    }
                }
            }
        }

        public ProfileModel GetProfile(string userName)
        {
            //burcar informação pessoal
            User u = new User();
            u =_provider.GetUser(userName);
            ProfileModel model = new ProfileModel(u);
            //buscar grupo de "amigos"
            foreach (Follower f in db.Followers)
            {
                if (f.FollowerID  == u.UserID)
                {
                    PublisherModel pm = new PublisherModel();
                    pm.Username = db.Users.Single(a => a.UserID == f.BroadcasterID).Username;
                    pm.UserID = f.BroadcasterID;
                    //pm.Photograph = db.Users.Single(a => a.UserID == f.BroadcasterID).Foto;
                    model.Publishers.Add(pm);
                }
            }
            return model;
        }

        public int GetUserID(string username)
        {
            return _provider.GetUser(username).UserID;
        }
    }

    public interface IFormsAuthenticationService
    {
        void SignIn(string userName, bool createPersistentCookie);
        void SignOut();
    }

    public class FormsAuthenticationService : IFormsAuthenticationService
    {
        public void SignIn(string userName, bool createPersistentCookie)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");

            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }


    #endregion

    #region Validation
    public static class UserValidation
    {
        public static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
    }

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
    public sealed class PropertiesMustMatchAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = "'{0}' and '{1}' do not match.";
        private readonly object _typeId = new object();

        public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty)
            : base(_defaultErrorMessage)
        {
            OriginalProperty = originalProperty;
            ConfirmProperty = confirmProperty;
        }

        public string ConfirmProperty { get; private set; }
        public string OriginalProperty { get; private set; }

        public override object TypeId
        {
            get
            {
                return _typeId;
            }
        }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
                OriginalProperty, ConfirmProperty);
        }

        public override bool IsValid(object value)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
            object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
            object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
            return Object.Equals(originalValue, confirmValue);
        }
    }

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class ValidatePasswordLengthAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = "'{0}' must be at least {1} characters long.";
        private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength;

        public ValidatePasswordLengthAttribute()
            : base(_defaultErrorMessage)
        {
        }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
                name, _minCharacters);
        }

        public override bool IsValid(object value)
        {
            string valueAsString = value as string;
            return (valueAsString != null && valueAsString.Length >= _minCharacters);
        }
    }


    //nao esta a ser usado de momento seria opçao ideal, como o upload da imagem é feito em paralelo esta ainda nao se encontra no modelo na validaçao
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class ValidImage : ValidationAttribute
    {
        private const string _defaultErrorMessage = "Photograh must be a suported Image File.";

        public ValidImage()
            : base(_defaultErrorMessage)
        {
        }

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }
            var test = (HttpPostedFileBase)value;
            if (test.ContentType.ToLower().StartsWith("image") == false)
            {
                return false;
            }

            return true;
        }
    }
    #endregion

}
